package com.ywy.servlet;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ywy.config.JDBC;

public class UserServlet extends HttpServlet {

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action"); // 获取action参数值
		if ("login".equals(action)) {
			this.login(request, response); // 用户登录
		} else if ("exit".equals(action)) {
			this.exit(request, response); // 安全退出
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * 用户注册的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void register(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("user"); // 获取用户名
		String pwd = request.getParameter("pwd"); // 获取密码
		String email = request.getParameter("email"); // 获取E-mail地址
		String abode = request.getParameter("abode"); // 获取居住地
		String message = ""; // 保存提示信息的变量
		String url = ""; // 保存返回地址的变量
		JDBC conn = new JDBC(); // 创建数据库连接对象
		String sql = "SELECT * FROM tb_user WHERE name='" + name + "'";
		ResultSet rs = conn.executeQuery(sql); // 查询用户名是否被注册
		try {
			if (rs.next()) {
				message = "该用户名已经被注册！";
				url = "register.jsp";
			} else {
				String sql_ins = "INSERT INTO tb_user (name,pwd,email,abode) VALUES('"
						+ name
						+ "','"
						+ pwd
						+ "','"
						+ email
						+ "','"
						+ abode
						+ "')";
				int rtn = conn.executeUpdate(sql_ins); // 将用户信息保存到数据表中
				System.out.println(sql_ins);
				if (rtn > 0) {
					message = "用户注册成功！";
					url = "login.jsp";
				} else {
					message = "用户注册失败";
					url = "register.jsp";
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			conn.close();
		}
		request.setAttribute("message", message); // 将提示信息保存到HttpServletRequest中
		request.setAttribute("url", url); // 将返回地址保存到HttpServletRequest中
		request.getRequestDispatcher("register_ok.jsp").forward(request,
				response);
	}

	/**
	 * 用户登录的方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("user"); // 获取用户名
		String pwd = request.getParameter("pwd"); // 获取密码
		String message = ""; // 保存提示信息的变量
		JDBC conn = new JDBC(); // 创建数据库连接对象
		String sql = "SELECT * FROM tb_user WHERE name='" + name + "'";
		ResultSet rs = conn.executeQuery(sql); // 根据用户名查询用户
		try {
			int id = 0;
			if (rs.next()) {			//当输入的用户名存在
				id = rs.getInt("id");		//获取用户ID
				if (pwd.equals(rs.getString("pwd"))) {
					HttpSession session = request.getSession();
					session.setAttribute("user", name); // 保存用户名到session中
					session.setAttribute("id", id);		// 保存用户ID到session中
					request.getRequestDispatcher("addressListServlet?action=query")
							.forward(request, response);
					return;	//此处必须加入return语句，否则程序将抛出java.lang.IllegalStateException:Cannot forward after response has been committed异常

				} else {
					message = "您输入的用户名或密码错误！";
				}
			} else {
				message = "您输入的用户名或密码错误！";
			}
		} catch (SQLException e) {
			e.printStackTrace();
			message = "登录失败！";
		} finally {
			conn.close();		// 关闭数据库连接
		}
		request.setAttribute("message", message); // 将提示信息保存到HttpServletRequest中
		request.getRequestDispatcher("deal.jsp").forward(request, response);
	}

	public void exit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.invalidate();
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}
}
